﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI.WebControls;
using Module.Core.Common;
using Module.Core.DAO;
using Module.Core.EntitiesInfo;
using Module.Common.Models;

namespace Module.Core.BusinessLogic
{
    public class MemberBL
    {
        /// <summary>
        /// Saves a record to the Member table.
        /// </summary>
        public static int Insert(MemberInfo memberInfo)
        {
            try
            {
                return new MemberDAO().Insert(memberInfo);
            }
            catch (Exception ex)
            {
                throw;
            }

        }



        /// <summary>
        /// Saves a record to the Member table.
        /// </summary>
        public static void Update(MemberInfo memberInfo)
        {
            try
            {
                new MemberDAO().Update(memberInfo);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static void UpdateCheckType(int idMember, int checktype)
        {
            try
            {
                new MemberDAO().UpdateCheckType(idMember, checktype);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        
        public static void UpdateLeftRight(string codeMember, string leftRight)
        {
            try
            {
                new MemberDAO().UpdateLeftRight(codeMember,leftRight);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static void UpdateCodeMemberParent(string codeMember, int idMember)
        {
            try
            {
                new MemberDAO().UpdateCodeMemberParent(codeMember, idMember);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        
        public static void UpdateSumNoteTree(string id,int sumNoteTree)
        {
            try
            {
                new MemberDAO().UpdateSumNoteTree(id, sumNoteTree);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        /// <summary>
        /// Delete a record from the Member table.
        /// </summary>
        public static void Delete(int idMember)
        {
            try
            {
                new MemberDAO().Delete(idMember);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        /// <summary>
        /// Thay đổi mật khẩu
        /// </summary>
        public static void ChangesPass(string email, string pass)
        {
            try
            {
                new MemberDAO().ChangesPass(email, pass);
            }
            catch (Exception ex)
            {
                throw;
            }

        }


        /// <summary>
        /// Lấy chi tiết bản ghi
        /// </summary>
        /// <param name="param"></param>
        /// <param name="type">Type=1 truyền vào email, type=2 truyền vào Idmember</param>
        /// <returns></returns>
        public static MemberInfo Select(string param, int type)
        {
            try
            {
                return new MemberDAO().Select(param, type);
            }
            catch (Exception)
            {              
            }
            return null;
        }
        public static CHRTList<MemberInfo> SelectList(string param, int type)
        {
            try
            {
                return new MemberDAO().SelectList(param, type);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        //Hiện thị thông tin cá nhân
        public static MemberInfo SelectProFile(string email)
        {
            try
            {
                return new MemberDAO().SelectProFile(email);
            }
            catch (Exception)
            {             
            }
            return null;

        }
        //update thông tin cá nhân
        public static void UpdateProfile(MemberInfo memberInfo)
        {
            try
            {
                new MemberDAO().UpdateProfile(memberInfo);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static DataTable Bonus(string codeMember)
        {
            try
            {
                return new MemberDAO().Bonus(codeMember);
            }
            catch (Exception)
            {              
            }
            return null;
        }
        public static void MemberUpdateBonus(int checktype, string codeMember, float goldBonus)
        {
            try
            {
                new MemberDAO().MemberUpdateBonus(checktype, codeMember, goldBonus);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        
        //hiện thị 10 thành viên đăng ký mới nhất
        public static DataTable DisplayTop20(int status)
        {
            try
            {
                return new MemberDAO().DisplayTop20(status);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public static DataTable DisplayMember(string email)
        {
            try
            {
                return new MemberDAO().DisplayMember(email);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        //Khi nhập mã thành viên thì hiện thị ra tên thành viên

        public static DataTable GetRecords(string codeMember, int param)
        {
            try
            {
                return new MemberDAO().GetRecords(codeMember, param);
            }
            catch (Exception ex)
            {
                throw;
            }

        }


        /// <summary>
        /// Selects all records from the Member table.
        /// </summary>
        public static CHRTList<MemberInfo> SelectAll(int status)
        {
            try
            {
                return new MemberDAO().SelectAll(status);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        public static int GetCount(string email, int status)
        {
            try
            {
                return new MemberDAO().GetCount(email, status);
            }
            catch (Exception)
            {

                throw;
            }
        }

        public static int GetCountLeftRight(string codeMember, string leftRight)
        {
            try
            {
                return new MemberDAO().GetCountLeftRight(codeMember, leftRight);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// Lấy tổng số Gold trong tài khoản 
        /// </summary>
        /// <param name="email"></param>        
        /// <returns></returns>
        public static int GetGold(string email)
        {
            try
            {
                return new MemberDAO().GetGold(email);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// Tính tổng tiền: gồm tiền gốc + tiền thưởng khi nâng cấp
        /// </summary>
        /// <param name="memberInfo"></param>
        /// <returns></returns>
       public static int TongTien(MemberInfo memberInfo)
        {
            int tong = 0;
            if(memberInfo !=null)
            {
                if(memberInfo.Checktype > 0 && memberInfo.GoldBonus > 0)
                {
                    tong = memberInfo.PriceMount + int.Parse(memberInfo.GoldBonus.ToString());
                }
                else
                {
                    tong = memberInfo.PriceMount;
                }
            }
            return tong;
        }
        /// <summary>
        /// Cộng số tiền người nhận và trừ số tiền người chuyển khoản
        /// </summary>
        /// <param name="type">type=1</param>
        /// <param name="emailChuyen">Email người chuyển tiền</param>
        /// <param name="emailNhan">Email người nhận tiền</param>
        /// <param name="sotienchuyen">Số tiền cần chuyển</param>
        
       //Chuyển gold qua tài khoản bằng email
       public static void UpdateGold(int type, string codeMember_from, string codeMember_To, int sotienchuyen)
        {
            try
            {
                new MemberDAO().UpdateGold(type, codeMember_from, codeMember_To, sotienchuyen);
            }
            catch (Exception)
            {

                throw;
            }
        }
        //Cộng tiền khuyến mãi cho khách hàng đăng ký và giới thiệu cho 10 người
       public static void Member_UpdatePromotional(int type, string codeMember, double sotienchuyen)
       {
           try
           {
               new MemberDAO().Member_UpdatePromotional(type, codeMember, sotienchuyen);
           }
           catch (Exception)
           {

               throw;
           }
       }
        //Chuyển gold qua tài khoản ATM
        public static void UpdateGoldATM(int type, string codeMemberFrom, string sotaikhoan, int sotienchuyen)
        {
            try
            {
                new MemberDAO().UpdateGoldATM(type, codeMemberFrom, sotaikhoan, sotienchuyen);
            }
            catch (Exception)
            {

                throw;
            }
        }

        //update khi quên mật khẩu
        public static void MemberUpdatePassword(string email, string password)
        {
            try
            {
                new MemberDAO().MemberUpdatePassword(email, password);
            }
            catch (Exception)
            {

                throw;
            }
        }
        //update gold khi nâng cấp

        public static void UpdateNapGold(int idMember,int type, string email, float sotienchuyen,int param)
        {
            try
            {
                new MemberDAO().UpdateNapGold(idMember,type, email, sotienchuyen,param);
            }
            catch (Exception)
            {

                throw;
            }
        }
        //update gold  trong tài khoản khi nạp tiền
        public static void UpdateNapGoldMember(int type, string email, float sotienchuyen)
        {
            try
            {
                new MemberDAO().UpdateNapGoldMember(type, email, sotienchuyen);
            }
            catch (Exception)
            {

                throw;
            }
        }


        public static CHRTList<MemberInfo> SearchAll(string email, int status, int from, int to, int checkType, DateTime createdOnFrom, DateTime createdOnTo)
        {
            try
            {
                return new MemberDAO().SearchAll(email, status, from, to, checkType, createdOnFrom, createdOnTo);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        public static DataSet FillListMember(int idMember,int leve,int checktype)
        {
            try
            {
                DataSet ds_source = new DataSet();
                DataTable dt = new DataTable();
                DataRow row = null;
                DataColumn FullName = new DataColumn("FullName", typeof (string));
                dt.Columns.Add(FullName);
                DataColumn FullNameSelected = new DataColumn("FullNameSelected", typeof(string));
                dt.Columns.Add(FullNameSelected);               
                DataColumn PriceMount = new DataColumn("PriceMount", typeof (string));
                dt.Columns.Add(PriceMount);
                DataColumn CodeMemberParent = new DataColumn("CodeMemberParent", typeof (string));
                dt.Columns.Add(CodeMemberParent);
                

                List<MemberInfo> list = GetParentMember(0,idMember, leve);              
                if (list.Count > 0)
                {
                    foreach (MemberInfo info in list)
                    {
                        ListItem _item = new ListItem();
                        _item = new ListItem(info.FullName, info.IdMember.ToString());
                        _item.Attributes.Add("Level", "1");
                        row = dt.NewRow();                                               
                        dt.Rows.Add(row);
                        GetSub_Items(checktype,_item, info.IdMember, 1, row, dt);
                        row["FullName"] = "[1] " + info.IdMember + " - " + info.FullName.ToString();
                        if(info.Checktype==1)
                            row["FullNameSelected"] = "<b style='color:red'>[1] " + info.IdMember + " - " + info.FullName.ToString() + "</b>";
                        else if (info.Checktype == 2)
                            row["FullNameSelected"] = "<span style='color:Blue'>[1] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                        else if (info.Checktype == 3)
                            row["FullNameSelected"] = "<span style='color:#A1B403'>[1] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                        else
                        {
                            row["FullNameSelected"] = "[1] " + info.IdMember + " - " + info.FullName.ToString();
                        }
                        row["CodeMemberParent"] = info.CodeMemberParent;        
                    }
                }
                ds_source.Tables.Add(dt);
                return ds_source;
            }
            catch (Exception ex)
            {
                throw;
            }
        }               
        private static void GetSub_Items(int checktype,ListItem curItem, int idMember,int leve, DataRow row, DataTable dt)
        {
            try
            {
                List<MemberInfo> list = GetParentMember(0, idMember, leve);
                if (list.Count > 0)
                {
                    int _level = ObjConvertUtility.ToInt32(curItem.Attributes["Level"]);
                    _level++;
                    foreach (MemberInfo info in list)
                    {
                        if (checktype == 1 && _level <= 10)//  Nếu là thành viên kim cương, hiển thị 10 đời
                        {
                            row = dt.NewRow();
                            ListItem _item = new ListItem();
                            _item = new ListItem(ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString(), info.IdMember.ToString());
                            _item.Attributes.Add("Level", _level.ToString());
                            dt.Rows.Add(row);
                            GetSub_Items(checktype,_item, info.IdMember, 1, row, dt);
                            row["FullName"] = _item;
                            if(info.Checktype==1)
                                row["FullNameSelected"] = "<b style='color:red'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</b>";
                            else if(info.Checktype==2)
                                row["FullNameSelected"] = "<span style='color:Blue'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else if (info.Checktype == 3)
                                row["FullNameSelected"] = "<span style='color:#A1B403'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else
                            {
                                row["FullNameSelected"] =_item;
                            }
                            row["CodeMemberParent"] = info.CodeMemberParent;
                            if(_level==10) return;
                        }
                        else if (checktype == 2 && _level <= 8)// thành viên vàng hiển thị đến đời 8
                        {
                            row = dt.NewRow();
                            ListItem _item = new ListItem();
                            _item = new ListItem(ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString(), info.IdMember.ToString());
                            _item.Attributes.Add("Level", _level.ToString());
                            dt.Rows.Add(row);
                            GetSub_Items(checktype,_item, info.IdMember, 1, row, dt);
                            row["FullName"] = _item;
                            if (info.Checktype == 1)
                                row["FullNameSelected"] = "<b style='color:red'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</b>";
                            else if (info.Checktype == 2)
                                row["FullNameSelected"] = "<span style='color:Blue'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else if (info.Checktype == 3)
                                row["FullNameSelected"] = "<span style='color:#A1B403'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else
                            {
                                row["FullNameSelected"] = _item;
                            }
                            row["CodeMemberParent"] = info.CodeMemberParent;
                        }
                        else if (checktype == 3 && _level <= 6)// thành viên bạc hiển thị đến đời 6
                        {
                            row = dt.NewRow();
                            ListItem _item = new ListItem();
                            _item = new ListItem(ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString(), info.IdMember.ToString());
                            _item.Attributes.Add("Level", _level.ToString());
                            dt.Rows.Add(row);
                            GetSub_Items(checktype,_item, info.IdMember, 1, row, dt);
                            row["FullName"] = _item;
                            if (info.Checktype == 1)
                                row["FullNameSelected"] = "<b style='color:red'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</b>";
                            else if (info.Checktype == 2)
                                row["FullNameSelected"] = "<span style='color:Blue'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else if (info.Checktype == 3)
                                row["FullNameSelected"] = "<span style='color:#A1B403'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else
                            {
                                row["FullNameSelected"] = _item;
                            }
                            row["CodeMemberParent"] = info.CodeMemberParent;
                        }
                        else if (checktype == 0 && _level <= 10)// thành viên miễn phí hiển thị đến đời 10
                        {
                            row = dt.NewRow();
                            ListItem _item = new ListItem();
                            _item = new ListItem(ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString(), info.IdMember.ToString());
                            _item.Attributes.Add("Level", _level.ToString());
                            dt.Rows.Add(row);
                            GetSub_Items(checktype,_item, info.IdMember, 1, row, dt);
                            row["FullName"] = _item;
                            if (info.Checktype == 1)
                                row["FullNameSelected"] = "<b style='color:red'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</b>";
                            else if (info.Checktype == 2)
                                row["FullNameSelected"] = "<span style='color:Blue'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else if (info.Checktype == 3)
                                row["FullNameSelected"] = "<span style='color:#A1B403'>" + ObjMiscUtility.StringIndent(_level) + "[" + _level + "] " + info.IdMember + " - " + info.FullName.ToString() + "</span>";
                            else
                            {
                                row["FullNameSelected"] = _item;
                            }
                            row["CodeMemberParent"] = info.CodeMemberParent;                          
                        }
                                               
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        public static int GetLeveMember(string codeMember)
        {
            try
            {
                int _level = 0;
                List<MemberInfo> list = GetParentLeveMember(1, codeMember);
                if (list.Count > 0)
                {
                    foreach (MemberInfo info in list)
                    {
                        ListItem _item = new ListItem();
                        _item = new ListItem(info.FullName);
                        _item.Attributes.Add("Level", Convert.ToString(info.Leve));
                        return GetSub_ItemsLeve(_item, info.CodeMember);
                    }
                    return _level;
                }

                return 0;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        //Check email
        public static bool CheckEmail(string email, int param)
        {
            try
            {
                return new MemberDAO().CheckEmail(email,param);
            }
            catch (Exception ex)
            {
                throw;
            }

        }
        //Check PhoneNumber
        public static bool CheckPhoneNumber(string phoneNumber,int param)
        {
            try
            {
            
                return new MemberDAO().CheckPhoneNumber(phoneNumber,param);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        //Check CMTND
        public static bool CheckCMTND(string cmtnd, int param)
        {
            try
            {

                return new MemberDAO().CheckCMTND(cmtnd, param);
            }
            catch (Exception ex)
            {
                throw;
            }

        }

        

        private static int GetSub_ItemsLeve(ListItem curItem, string codeMember)
        {
            try
            {

                int _level = ObjConvertUtility.ToInt32(curItem.Attributes["Level"]);
                List<MemberInfo> list = GetParentLeveMember(0, codeMember);
                _level++;
                if (list.Count > 0)
                {
                    foreach (MemberInfo info in list)
                    {
                        ListItem _item = new ListItem();
                        _item.Attributes.Add("Level", _level.ToString());

                        GetSub_ItemsLeve(_item, info.CodeMember);
                        return _level;
                    }
                }

                return _level;
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        

        public static CHRTList<MemberInfo> GetParenMatrix(string codeMember)
        {
            return new MemberDAO().GetParenMatrix(codeMember);
        }

        public static CHRTList<MemberInfo> GetParentMember(int type, int idMember, int leve)
        {
            return new MemberDAO().GetParentMember(type, idMember, leve);
        }
        public static CHRTList<MemberInfo> GetParentLeveMemberFull(string idMember, int checkType)
        {
            return new MemberDAO().GetParentLeveMemberFull(idMember, checkType);
        }
        public static DataTable GetMemberList10(int beginNumber, int endNumber, int isTotal)
        {
            return new MemberDAO().Get10Row(beginNumber, endNumber, isTotal);
        }
        public static CHRTList<MemberInfo> GetParentLeveMemberFull_Search(string codeMember, string keySearch)
        {
            return new MemberDAO().GetParentLeveMemberFull_Search(codeMember,keySearch);
        }
        public static CHRTList<MemberInfo> GetParentLeveMemberTop(string codeMember)
        {
            return new MemberDAO().GetParentLeveMemberFullTop(codeMember);
        }      

        public static CHRTList<MemberInfo> GetParentLeveMember(int type, string codeMember)
        {
            return new MemberDAO().GetParentLeveMember(type, codeMember);
        }
               
        #region Thống kê level
        public static DataTable MemberCountLevel()
        {

            return new MemberDAO().MemberCountLevel();
        }

        #endregion

        public static int GetTotalMember()
        {

            return new MemberDAO().GetTotalMember();
        }

        public static void SaveCookie(string userName)
        {
            HttpCookie Cookie_Account;
            if (HttpContext.Current.Request.Cookies["CookieUser"] != null)
                HttpContext.Current.Response.Cookies["CookieUser"].Expires = DateTime.Now.AddDays(-1);

            Cookie_Account = new HttpCookie("CookieUser");
            Cookie_Account.Expires = DateTime.Now.AddHours(1);

            //EnCode AccountCode và Accountpassword trường khi lưu xuống Cookie
            Cookie_Account.Values.Add("userName", userName);
            HttpContext.Current.Response.Cookies.Remove("CookieUser");
            HttpContext.Current.Response.Cookies.Add(Cookie_Account);
        }
        public static string GetValue()
        {
            string valueCookie = string.Empty;
            string userName = string.Empty;
            if (HttpContext.Current.Request.Cookies["CookieUser"] != null)
            {
                valueCookie = HttpContext.Current.Request.Cookies["CookieUser"].Value;
                if (valueCookie != null && valueCookie != "")
                {
                    userName = valueCookie.Replace("userName=", "");
                }
            }
            return userName;
        }
                               
        public static void DeleteCookie()
        {
            //Nếu Cookie tồn tại thì xóa cookie đó đi
            if (HttpContext.Current.Response.Cookies["CookieUser"] != null)
                HttpContext.Current.Response.Cookies["CookieUser"].Expires = DateTime.Now.AddDays(-1);
        }


    }
}
